package com.leetroll.admin.security;

import com.alibaba.fastjson.JSONObject;
import com.leetroll.common.constant.CharConstant;
import com.leetroll.common.enums.ECode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author qdy
 * @Date 2023/11/10 14:26
 * 权限不足异常处理
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        String msg = "请求访问"+request.getRequestURI()+"认证失败，无法访问系统资源";
        response.setStatus(ECode.SUCCESS);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Map<String, Object> result = new HashMap<>(CharConstant.NUM_THREE);
        result.put("code", ECode.UNAUTHORIZED);
        result.put("msg", msg);
        result.put("data", "当前用户权限不足！请联系qdy");
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}
